import React, { Component } from 'react';
import {
	Form,
	Modal,
	Select,
	Radio,
	Input,
	Table,
	Tooltip,
	Button,
} from 'antd';
import { FilterOutlined, FilterFilled, ClearOutlined } from '@ant-design/icons';
import { EditableRow,EditableCell } from './EditTaleComponent';
// import { FormInstance } from 'antd/lib/form';
import { getConnectList, getSourceTables, getSourceTableSchema, joinResource, resourceUpdate } from 'src/services/DataManage';
// import {  SearchOutlined } from '@ant-design/icons';
import _ from 'lodash';
import FilterField from 'src/pages/DataManage/DataArrange/components/FilterField';
// import Icon from 'antd/lib/icon';

// import { FIcon } from 'src/pages/DataManage/DataArrange/components/SvgComponent';

interface Iprops {
	modalTitle:string
	visible:boolean
	handleOk:any
	addNodeFunc:any
	etlId:any
	forwardRef:any
	data:any
	maxCount:any
}


interface Tprops {
	onChange:any
	selectedRowKeys:any
	columns:any
	feildData:any
	handleSave:any
}

const FIcon = () => (
	<svg  className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16">
		<path
			d="M512 77C271.8 77 77 271.8 77 512c0 240.2 194.8 435 435 435 240.2 0
			435-194.8 435-435C947 271.8 752.2 77 512 77L512 77zM509.2 816.4c-35.4 0-64.2-28.2-64.2-62.9s28.7-62.9 64.2-62.9c35.4
			0 64.2 28.2 64.2 62.9S544.7 816.4 509.2 816.4L509.2 816.4zM681.6 460.5c-12.6 19.8-39.3 46.7-80.3 80.8-21.2 17.6-34.4
			31.8-39.5 42.6-5.1 10.7-7.5 29.9-7 57.6l-91.4 0c-0.2-13.1-0.4-21.1-0.4-24 0-29.6 4.9-53.9 14.7-73 9.8-19.1 29.4-40.6
			 58.7-64.4 29.3-23.9 46.9-39.5 52.6-46.9 8.8-11.7 13.3-24.6 13.3-38.6 0-19.5-7.9-36.2-23.5-50.2-15.6-13.9-36.8-20.9-
			63.3-20.9-25.6 0-477.3-64.2 21.8-17.2 14.5-32 46.5-35.5 66.3-3.3 18.7-93.4 26.6-92.3-11.3 1.1-37.9 20.8-79 54.6-108.8
			33.8-29.8 78.2-44.7 133.1-44.7 57.8
			  0 103.7 15.1 137.9 45.3 34.2 30.2 51.2 65.3 51.2 105.4C700.4 419.7 694.1 440.7 681.6 460.5L681.6 460.5z"
			p-id="1157" fill="#78BF03"></path>
	</svg>
);



const TableComp = ( { selectedRowKeys,onChange,columns,feildData,handleSave }:Tprops ) => {

	const tableChange = ( selectedRowKeys ) => {
		onChange( { selectedRowKeys } );
	};
	
	const components = {
		body: {
			row: EditableRow,
			cell: EditableCell
		},
	};

	const columnsRes = columns.map( col => {
		if ( !col.editable ) {
			return col;
		}
		return {
			...col,
			onCell: record => ( {
				record,
				editable: col.editable,
				dataIndex: col.dataIndex,
				title: col.title,
				handleSave: handleSave,
			} ),
		};
	} );


	return (
		<Table columns={columnsRes}
			   pagination={false}
			   components={components}
			// showHeader={false}
			   scroll={{ y: 300 }}
			   rowSelection={{
				   selectedRowKeys: selectedRowKeys,
				   onChange: tableChange,
			   }}
			   dataSource={feildData}/>
	);


};




class AddDataModal extends Component<Iprops,any> {
	
	state = {
		filterModalVisible: false, //数据源筛选组件
		companyPage: 1,
		companyData: [],
		companyTotal: 0,
		sourceDbName: '',

		tableData: [],
		dbId: '',
		tableName: '',
		feildData: [],
		selectedRowKeys: [],
		tableDataSource: [],
		editId: '',
		sourceType: '',
		curField: {
			desc: '-',
			type: 'Text'
		},
		conditions: [],
	}

	// formRef = React.createRef<FormInstance>()
	
	//提交form
	handelForm = () => {
		let fd = JSON.parse( JSON.stringify( this.state.feildData ) );
		this.props.forwardRef.current.validateFields().then( value => {
			let tmpValue = JSON.parse( JSON.stringify( value ) );
			tmpValue['modelId'] = this.props.etlId;
			tmpValue['fields'] = tmpValue['fields']['selectedRowKeys'].map( item => {
				return {
					...fd[item],
					desc: this.state.tableDataSource[item].desc
				};
			} );
			// tmpValue['fields'] = fd.filter( item => tmpValue['fields']['selectedRowKeys'].includes( item.name ) );
			if ( this.state.editId ) { // 编辑时
				let modelId = tmpValue.modelId;
				delete tmpValue.modelId;
				resourceUpdate( { data: { ...tmpValue, componentCode: this.props.data.code, conditions: this.state.conditions } } ).then(
					info => {
						if ( info.data.success ) {
							this.props.addNodeFunc( { ...info.data.data,...tmpValue,modelId, oldId: this.state.editId,nodeType: 'database', conditions: this.state.conditions }, true );
							// this.props.addNodeFunc( { ...info.data.data,...tmpValue,modelId,nodeType: 'database',oldId: this.state.editId }, true );
							this.handelReset();
						}
					}
				);
			} else { //新增
				joinResource( { data: { ...tmpValue, conditions: this.state.conditions } } ).then(
					info => {
						if ( info.data.success ) {
							this.props.addNodeFunc( { ...info.data.data,...tmpValue,nodeType: 'database',conditions: this.state.conditions } );
							this.handelReset();
						}
					}
				);
			}
		} );
	}
	
	handelReset = () => {
		this.setState( { sourceDbName: '', tableData: [], conditions: [],
			dbId: '', tableName: '',tableDataSource: [], feildData: [],selectedRowKeys: [], editId: '' } );
		this.props.handleOk( 'visible',false );
		this.props.forwardRef.current.resetFields();
	}

	handleSave = row => {
		const newData = [ ...this.state.tableDataSource ];
		const index = newData.findIndex( item => row.key === item.key );
		const item = newData[index];
		newData.splice( index, 1, {
			...item,
			...row,
		} );

		this.setState( { tableDataSource: newData } );
	};
	
	
	getCompanyData = async () => {
		//ENABLE("ENABLE", "有效"),
		//DISABLE("DISABLE", "失效");
		let data = { 'page': this.state.companyPage,'size': 1000,'name': '',effect: 'ENABLE' };
		if ( this.state.companyData.length <= this.state.companyTotal ) {
			const info = await getConnectList( data );
			if ( info.data.success ) {
				this.setState( {
					companyData: [ ...this.state.companyData,...info.data.data.rows ],
					companyTotal: info.data.data.total,
				} );
			}
		}
	}

	//获取表数据字段
	tableSchema = async params => {
		const info = await getSourceTableSchema( params );
		if ( info.data.success ) {
			const data = info.data.data.columns;
			let selectedRowKeys = data.map( ( item,index ) => index );
			//编辑时
			if ( this.state.editId ) {
				selectedRowKeys = this.props.data.fields.map( item => {
					return _.findIndex( data, { name: item.name } );
				} );
			}
			this.setState( { feildData: data,
				// selectedRowKeys: data.map( ( item,index ) => index ),
				selectedRowKeys,
				tableDataSource: data.map( ( item,index ) => {return { key: index, desc: item.desc,name: item.name };}  ) },
			() => {
				this.props.forwardRef.current.setFieldsValue( { fields: { selectedRowKeys: this.state.selectedRowKeys } } );
			} );
		}
	}

	//获取侧边栏数据表选项数据
	tablesData = async params => {
		const info = await getSourceTables( params );
		if ( info.data.success ) {
			let data = info.data.data;
			this.setState( {
				tableData: data ,
			} );
		}
	}

	//处理数据原选择
	handleSelectSource = value => {
		this.props.forwardRef.current.resetFields( [ 'fields','offsetField','tableName' ]  );
		this.setState( { sourceDbName: '', tableData: [],
			dbId: '', tableName: '',tableDataSource: [], feildData: [],selectedRowKeys: [] } );
		let db = this.state.companyData.filter( item => item.id === value )[0];
		console.log( db );
		
		this.setState( { dbId: value,
			sourceType: db.type,
			sourceDbName: db.dbName } ,
		() => {
			this.tablesData( { data: this.state.dbId } );
		}
		);
	}
	
	handleSelectTable = value => {
		this.props.forwardRef.current.resetFields( [ 'fields','offsetField' ]  );
		this.setState( {
			tableName: value,
		} );
		//获取 预览表 表头数据
		let data = { data: { 'dbId': this.state.dbId,
			'tableName': value } };
		this.tableSchema( data );
		
	}

	//多选
	onSelectChange = ( selectedRowKeys ) => {
		this.setState( { ...selectedRowKeys } );
	};

	//编辑初始化
	editInit = () => {
		// 不执行编辑初始化的条件
		if ( !this.props.visible || !( this.props.data && this.props.data.id ) || this.props.data.id === this.state.editId ) return;
		const data = this.props.data;
		const dbname = this.state.companyData.filter( item => item.id === data.sourceId )[0].dbName;
		this.setState( {
			editId: data.id,
			dbId: data.sourceId,
			sourceDbName: dbname,
			tableName: data.tableName,
			conditions: data.conditions || [],
		} );
		//获取表数据
		this.tablesData( { data: data.sourceId } );
		//获取 预览表 表头数据
		this.tableSchema( {
			data: { 'dbId': data.sourceId, 'tableName': data.tableName }
		} );
	};

	//数据筛选
	handleFilter = ( row ) => {
		if ( row ) {
			let data = _.find( this.state.feildData, { name: row.name } );
			if ( data ) {
				this.setState( {
					filterModalVisible: true,
					curField: data,
				} );
			};
		}
	};

	// 清除筛选
	clearFilter = ( row ) => {
		if ( !row ) return;
		let conditions = [ ...this.state.conditions ];
		this.setState( {
			conditions: conditions.filter( o => o.field !== row.name ),
		} );
	};

	// 数据筛选弹窗
	toggleFilterModal = ( value: boolean ) => {
		this.setState( {
			filterModalVisible: value,
		} );
	};

	//数据筛选字段处理
	handleCondition = ( data ) => {
		let conditions = [ ...this.state.conditions ];
		let fields = conditions.map( o => o.field );
		data.forEach( item => {
			/* let idx = fields.indexOf( item.field );
			if ( idx > -1 ) {
				conditions.splice( idx, 1 );
			} */
			fields.forEach( ( fd, idx ) => {
				if ( fd === item.field ) {
					// 删除对应字段 并用null占位
					conditions.splice( idx, 1, null );
				}
			} );
		} );
		// 过滤为null的值
		let arr = data.filter( o => o.values !== null );
		conditions.push( ...arr );
		this.setState( { conditions: conditions.filter( o => o !== null ) } );
	};
	
	componentDidMount(): void {
		this.getCompanyData();
	}

	getSnapshotBeforeUpdate(  prevProps: Readonly<Iprops>, prevState: Readonly<{}> ): any | null {
		let { data } = this.props;
		let changeObj = Object.create( null );

		//	判断数据字段是否变化了
		if ( JSON.stringify( prevProps.data ) !== JSON.stringify( data ) ) {
			changeObj.needEditInit = true;
		}

		return changeObj;
	}

	componentDidUpdate( prevProps: Readonly<Iprops>, prevState: Readonly<{}>, snapshot?: any ): void {
		if ( snapshot.needEditInit ) {
			this.editInit();
		}
	}


	render() {
		const layout = {
			labelCol: { span: 7 },
		};

		const columns = [
			{
				title: '全选',
				dataIndex: 'name',
				key: 'name'
			},
			{
				title:
					<div>
						<Tooltip placement="top" title={'点击文本可编辑别名'}>
							<span style={{ marginRight: '3px' }}>
								<FIcon/>
							</span>
						</Tooltip>
						<span>别名</span>
					</div>,
				dataIndex: 'desc',
				key: 'desc',
				editable: true
			},
			{
				title: '数据筛选',
				key: 'filter',
				render: ( record ) => {
					const fields = this.state.conditions.map( o => o.field );
					const hasCond = fields.indexOf( record.name ) > -1;
					return (
						<>
							<Tooltip placement="topRight" title="数据筛选">
								<Button
									type="text" icon={ hasCond ? <FilterFilled style={ { color: '#86bc25' } } /> : <FilterOutlined style={ { color: '#86bc25' } } /> }
									onClick={ () => this.handleFilter( record ) }>
								</Button>
							</Tooltip>
							{
								hasCond && (
									<Tooltip placement="topRight" title="清除筛选">
										<Button
											style={ { marginLeft: 0, } }
											type="text" icon={ <ClearOutlined style={ { color: '#86bc25' } } /> }
											onClick={ () => this.clearFilter( record ) }>
										</Button>
									</Tooltip>
								)
							}
						</>
					);
				}
			},
		];

		// const rowSelection = {
		// 	selectedRowKeys: this.state.selectedRowKeys,
		// 	onChange: this.onSelectChange,
		// };
		const maxCount = this.props.maxCount;
		let count = maxCount.length > 0
			?Math.max.apply( null, maxCount.map(
				item => {
					let num = parseInt( item.replace( '表','' ) );
					if ( num ) {
						return num + 1;
					} else {
						return 0;
					}
				}
			) )
			:0;

		return (
			<Modal
				title={this.props.modalTitle}
				visible={this.props.visible}
				onOk={this.handelForm}
				onCancel={ this.handelReset}
				cancelText={'取消'}
				okText={'确定'}
				key={'modalForm'}
				width={550}
				mask={false}
				maskClosable={false}
			>
				<Form { ...layout } 
					  labelAlign='right' 
					  // ref={this.formRef}
					  ref={this.props.forwardRef}
					  key={'form'}
					  initialValues={{
						  // connectType: 1,
						  syncType: '1',
						  duplicate: '1',
						  componentName: `表${ count}`
					  }}
					  className='search-form'>
					<Form.Item
						name="sourceId"
						label="选择数据源"
					>
						<Select onChange={value => this.handleSelectSource( value ) }>
							{this.state.companyData.map( item => <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option> )}
						</Select>
					</Form.Item>
					<Form.Item
						// name="selectDB"
						label="数据库"
					>
						{this.state.sourceDbName}
					</Form.Item>
					<Form.Item
						name="tableName"
						label="选择表"
					>
						<Select onChange={value => this.handleSelectTable( value )} showSearch>
							{this.state.tableData.map( ( item,index ) => <Select.Option key={index} value={item}>{item}</Select.Option> )}
						</Select>
					</Form.Item>
					<Form.Item name="fields" label="选择需要加入的字段" 
							   rules={[ { required: true, message: '请选择需要加入的字段' } ]}>
						{/*<Checkbox.Group style={{ width: '100%' }}>*/}
						{/*	{*/}
						{/*		this.state.feildData.map(*/}
						{/*			( item,index ) => <Checkbox value={item.name} key={index}>{item.name}</Checkbox>*/}
						{/*		)*/}
						{/*	}*/}
						{/*</Checkbox.Group>*/}
						<TableComp onChange={this.onSelectChange}
								   handleSave={this.handleSave}
								   selectedRowKeys={this.state.selectedRowKeys}
								   columns={columns}
								   feildData={this.state.tableDataSource}/>
						
						{/*<Table columns={columns}*/}
						{/*	   pagination={false}*/}
						{/*	   // showHeader={false}*/}
						{/*	   scroll={{ y: 300 }}*/}
						{/*	   rowSelection={rowSelection}*/}
						{/*	   dataSource={this.state.feildData.map( ( item,index ) => {return { key: index, name: item.name };}  )} />*/}
					</Form.Item>

					{/*<Form.Item name="connectType" label="连接方式">*/}
					{/*	<Radio.Group>*/}
					{/*		<Radio value={1}>数据提取</Radio>*/}
					{/*	</Radio.Group>*/}
					{/*</Form.Item>*/}
					{/*刷新方式*/}
					<Form.Item name="syncType" label={<><FIcon/><span style={{ marginLeft: '5px' }}>刷新方式</span></>}>
						<Radio.Group>
							<Radio value={'1'}>全量</Radio>
							<Radio value={'2'}>增量</Radio>
							<Radio value={'0'}>直连</Radio>
						</Radio.Group>
					</Form.Item>
					{/*独立副本*/}
					<Form.Item name="duplicate" label={<><FIcon/><span style={{ marginLeft: '5px' }}>独立副本</span></>}>
						<Radio.Group>
							<Radio value={'1'}>是</Radio>
							<Radio value={'0'}>否</Radio>
						</Radio.Group>
					</Form.Item>
					{/*'增量标识字段'  */}
					{
						[ '7','8' ].indexOf( this.state.sourceType ) === -1 && (
							<Form.Item name="offsetField" rules={[ { required: true, message: '请选择增量标识字段' } ]}
							   label={<><FIcon/><span style={{ marginLeft: '5px' }}>增量标识字段</span></>}>
								<Select>{
									this.state.feildData.map( ( item,index ) => <Select.Option value={item.name} key={index}>{item.desc}</Select.Option> )
								}
								</Select>
							</Form.Item>
						)
					}
					<Form.Item name="componentName" label="组件名称">
						<Input/>
					</Form.Item>
				</Form>

				{/* 数据源筛选 */}
				<FilterField modalVisible={this.state.filterModalVisible}
					sourceId={this.state.dbId}
					tableName={this.state.tableName}
					curField={this.state.curField}
					conditions={this.state.conditions}
					toggleFilterModal={this.toggleFilterModal}
					handleCondition={this.handleCondition}
				></FilterField>
			</Modal>
		);
	}
}

export default AddDataModal;